package com.wlgc.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlgc.dao.UserDao;
import com.wlgc.entity.LoginUser;
import com.wlgc.entity.User;
import com.wlgc.util.JwtUtil;
import com.wlgc.util.RedisCache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;
    @Resource
    UserDao dao;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        Claims claims;
        //解析token
        String id;
        try {
          claims  = JwtUtil.parseJWT(token);


        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        try{
            id = claims.getSubject();
        }
        catch (ExpiredJwtException a)
        {
           id= a.getClaims().getSubject();
        }
     User user= dao.selectById(id);
        if(user==null)
        {
            filterChain.doFilter(request, response);
            return;
        }
       id=user.getId().toString();
        //从redis中获取用户信息
        String redisKey = "login:" +id ;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);

        if(Objects.isNull(loginUser)){
            filterChain.doFilter(request, response);
            return;
        }


        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}